package org.desktop.web.server.util;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.desktop.web.client.util.service.ReflectionService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ReflectionServiceImpl extends RemoteServiceServlet implements
		ReflectionService {

	static final Map<String, Class> primitives = new HashMap<String, Class>();

	static {
		primitives.put(boolean.class.getName(), boolean.class);
		primitives.put(short.class.getName(), short.class);
		primitives.put(int.class.getName(), int.class);
		primitives.put(long.class.getName(), long.class);
		primitives.put(char.class.getName(), char.class);
		primitives.put(double.class.getName(), double.class);
		primitives.put(float.class.getName(), float.class);
	}
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public Serializable setProperty(Serializable target, String propertyName,
			Serializable propertyValue, String objectType) {
		try {
			if (target != null) {
				String metName = new StringBuilder("set").append(
						StringUtils.capitalize(propertyName)).toString();
				Method set = target.getClass().getDeclaredMethod(
						metName,
						primitives.containsKey(objectType) ? primitives
								.get(objectType) : Class.forName(objectType));
				set.invoke(target, propertyValue);
				return target;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
